package com.prothink.threadproject.xiancheng;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockExample {

    // 两个锁
    private static final Lock lock1 = new ReentrantLock();
    private static final Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {

        // 线程1
        Thread thread1 = new Thread(() -> {
            try {
                // 尝试获取lock1
                lock1.lock();
                System.out.println("线程 1: 获得锁1");

                // 模拟执行任务
                Thread.sleep(50);

                // 尝试获取lock2
                lock2.lock();
                System.out.println("线程 1：获取的 lock2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock1.unlock();
                lock2.unlock();
            }
        });

        // 线程2
        Thread thread2 = new Thread(() -> {
            try {
                // 尝试获取lock2
                lock2.lock();
                System.out.println("线程 2：获取的 lock2");

                // 模拟执行任务
                Thread.sleep(50);

                // 尝试获取lock1
                lock1.lock();
                System.out.println("线程 2：获取的锁 1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock2.unlock();
                lock1.unlock();
            }
        });

        // 启动两个线程
        thread1.start();
        thread2.start();
    }
}
